package com.zhss.demo.redisson.lock;

import com.zhss.demo.redisson.RedissionHelp;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class FairLockDemo {
    public static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        RedissonClient redissionClient = RedissionHelp.getRedissionClient();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.err.println(Thread.currentThread().getId()+"...coming , time = " + System.currentTimeMillis());
                    RLock cjm_fairLock1 = redissionClient.getFairLock("cjm_fairLock");
                    if (atomicInteger.getAndIncrement() == 0) {
                        System.err.println(Thread.currentThread().getId() + " lock at time:" + System.currentTimeMillis());
                        cjm_fairLock1.lock();
                    } else {
                        try {
                            System.err.println(Thread.currentThread().getId() + " before lock at time:" + System.currentTimeMillis());
                            cjm_fairLock1.tryLock(10000, 40000, TimeUnit.MILLISECONDS);
                            System.err.println(Thread.currentThread().getId() + " after lock at time:" + System.currentTimeMillis());
                            if (Thread.currentThread().getId() != 55L) {
                                return;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        System.err.println(Thread.currentThread().getId()+"...sleep at time = " + System.currentTimeMillis());
                        TimeUnit.SECONDS.sleep(8);
                        System.err.println(Thread.currentThread().getId() + " weak up at time = " + System.currentTimeMillis());
                        cjm_fairLock1.lock();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        Thread t3 = new Thread(runnable);

//        System.err.println(t1.getId());
//        System.err.println(t2.getId());
//        System.err.println(t3.getId());

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        redissionClient.shutdown();
        System.err.println("system shut down at time = " + System.currentTimeMillis());
    }
}
